package server

import (
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	adminMenuApi "go-skeleton/api/admin/service/admin_menu"
	adminRoleApi "go-skeleton/api/admin/service/admin_role"
	adminUserApi "go-skeleton/api/admin/service/admin_user"
	langApi "go-skeleton/api/admin/service/lang"
	"go-skeleton/app/admin/service/internal/conf"
	"go-skeleton/app/admin/service/internal/service/admin_menu"
	"go-skeleton/app/admin/service/internal/service/admin_role"
	"go-skeleton/app/admin/service/internal/service/admin_user"
	"go-skeleton/app/admin/service/internal/service/lang"
	"go-skeleton/pkg/middleware/jwt"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
)

// NewGRPCServer new a gRPC server.
func NewGRPCServer(c *conf.Server, ca *conf.Auth, logger log.Logger, tp *tracesdk.TracerProvider,
	adminUser *admin_user.AdminUserService,
	menu *admin_menu.MenuService,
	role *admin_role.RoleService,
	lang *lang.LangService,
) *grpc.Server {
	var opts = []grpc.ServerOption{
		grpc.Middleware(
			recovery.Recovery(),
			tracing.Server(
				tracing.WithTracerProvider(tp)),
			logging.Server(logger),
			validate.Validator(),
			jwt.NewAuthServer(ca.AdminKey),
		),
	}
	if c.Grpc.Network != "" {
		opts = append(opts, grpc.Network(c.Grpc.Network))
	}
	if c.Grpc.Addr != "" {
		opts = append(opts, grpc.Address(c.Grpc.Addr))
	}
	if c.Grpc.Timeout != nil {
		opts = append(opts, grpc.Timeout(c.Grpc.Timeout.AsDuration()))
	}
	srv := grpc.NewServer(opts...)
	adminUserApi.RegisterAdminUserServiceServer(srv, adminUser)
	adminMenuApi.RegisterMenuServiceServer(srv, menu)
	adminRoleApi.RegisterRoleServiceServer(srv, role)
	langApi.RegisterLangServiceServer(srv, lang)
	return srv
}
